#include "AsyncListener.h"

U2L::AsyncListener::AsyncListener(void)
{
	m_listening = false;
	m_done = false;
	m_serverSocket = NULL;
	m_clientSocket = NULL;
}

U2L::AsyncListener::~AsyncListener(void)
{
}

void U2L::AsyncListener::Accept(sf::SocketTCP* _serverSocket, sf::SocketTCP* _clientSocket)
{
	if (_serverSocket != NULL &&
		_clientSocket != NULL &&
		!m_listening)
	{
		m_serverSocket = _serverSocket;
		m_clientSocket = _clientSocket;
		m_listening = true;
		m_done = false;
		this->Launch();
	}
}

bool U2L::AsyncListener::IsListening(void) const
{
	return m_listening;
}

bool U2L::AsyncListener::IsDone(void)
{
	if (m_done)
	{
		m_done = false;
		return true;
	}
	return false;
}

void U2L::AsyncListener::Run(void)
{
	try
	{
		if (m_serverSocket->Accept(*m_clientSocket) == sf::Socket::Done)
		{
			m_done = true;
		}
		m_serverSocket = NULL;
		m_clientSocket = NULL;
		m_listening = false;
	}
	catch (std::exception& err)
	{
		std::cerr << err.what() << std::endl;
	}
}